package pers.qianyu.module.image.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.qianyu.module.core.domain.image.dto.ImageLabelDTO;
import pers.qianyu.module.core.domain.image.entity.ImageLabelPO;
import pers.qianyu.module.core.domain.image.entity.LabelPO;
import pers.qianyu.module.image.dao.ImageLabelDao;
import pers.qianyu.module.image.dao.LabelDao;
import pers.qianyu.module.image.service.ImageLabelService;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author mizzle rain
 * @date 2021-04-22 14:13
 */
@Service("imageLabelService")
public class ImageLabelServiceImpl implements ImageLabelService {
    @Autowired
    private ImageLabelDao imageLabelDao;
    @Autowired
    private LabelDao labelDao;

    @Override
    public void insert(ImageLabelDTO imageLabelDTO) {
        ImageLabelPO imageLabelPO = new ImageLabelPO();
        imageLabelPO.setImageId(imageLabelDTO.getImageId());
        imageLabelPO.setLabelId(imageLabelDTO.getLabelId());
        Integer cnt = imageLabelDao.selectCount(new QueryWrapper<>(imageLabelPO));
        if (cnt > 0) {
            return;
        }
        imageLabelDao.insert(imageLabelPO);
    }

    @Override
    public void delete(ImageLabelDTO imageLabelDTO) {
        ImageLabelPO imageLabelPO = new ImageLabelPO();
        imageLabelPO.setImageId(imageLabelDTO.getImageId());
        imageLabelPO.setLabelId(imageLabelDTO.getLabelId());
        QueryWrapper<ImageLabelPO> wrapper = new QueryWrapper<>(imageLabelPO);
        imageLabelDao.delete(wrapper);
    }

    @Override
    public Set<String> getLabelsByImageId(Long imageId) {
        // 查询所有标签id
        QueryWrapper<ImageLabelPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("image_id", imageId);
        List<ImageLabelPO> imageLabelPOS = imageLabelDao.selectList(queryWrapper);
        Set<Long> labelIds = imageLabelPOS.stream()
                .map(ImageLabelPO::getLabelId)
                .collect(Collectors.toSet());
        // 查询所有标签
        QueryWrapper<LabelPO> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("id", labelIds);
        List<LabelPO> labelPOS = labelDao.selectList(queryWrapper2);
        Set<String> set = labelPOS.stream().map(LabelPO::getName).collect(Collectors.toSet());
        return set;
    }
}
